<?php

namespace app\ctrl;

/**
 * base64加解密
 */
class Base64 extends \app\ctrl\BaseController
{

    /**
     * 加密
     */
    public function jiami()
    {
        // 输出详情html内容
        $view = new \core\lib\View(VIEWS);
        return $view->render('base64_jiami', [
            'v' => time(),
            'url' => env('APP_BASEURL') . 'base64/doJiami',
            'backurl'=>env('APP_BASEURL') . 'base64/jiami',
        ]);
    }

    /**
     * 解密
     */
    public function jiemi()
    {
        // 输出详情html内容
        $view = new \core\lib\View(VIEWS);
        return $view->render('base64_jiemi', [
            'v' => time(),
            'url' => env('APP_BASEURL') . 'base64/doJiemi'
        ]);
    }

    /**
     * 处理加密
     * @param string $content 一个链接或一个文本
     */
    public function doJiami()
    {
        set_time_limit(0);
        $startTime = microtime(true);
        require_once(VENDOR . '/autoload.php');
        $params = post();
        $this->validate($params, [
            'content' => 'require',
        ]);
        $content = trim($params['content']);
        if (str_starts_with($content, 'http') && str_ends_with($content, '.txt')) {
            $content = @file_get_contents($content);
            if (empty($content)) {
                error('无法获取链接内容');
            }
        }
        $kaitou = strtolower(substr($content, 0, 5));
        if ($kaitou === '<?php') {
            $content = substr($content, 5);
        } elseif (substr($kaitou, 0, 2) === '<?') {
            $content = substr($content, 2);
        }
        $jiewei = strtolower(substr($content, -2));
        if ($jiewei == '?>') {
            $content = substr($content, 0, strlen($content) - 2);
        }
        // 移除首尾的空格和换行符
        $content = trim($content);
        $content = trim($content, PHP_EOL);

        $data['content'] = base64_encode($content);
        $endTime = microtime(true);
        $data['exectime'] = number_format($endTime - $startTime, 2);
        return $data;
    }

    /**
     * 处理解密
     * @param string $content 一个已加密的文本
     */
    public function doJiemi()
    {
        set_time_limit(0);
        $startTime = microtime(true);
        require_once(VENDOR . '/autoload.php');
        $params = post();
        $this->validate($params, [
            'content' => 'require',
        ]);
        $content = trim($params['content']);
        $data['content'] = base64_decode($content);
        $endTime = microtime(true);
        $data['exectime'] = number_format($endTime - $startTime, 2);
        return $data;
    }
}